$DC='xxxxxx.domain.internal'
$homefolder ="\\domain.internal\sharedfolders\users$\"
$erroractionpreference = "SilentlyContinue" #<-----------------Ignore Error Info
#<------------------------------------------------Determine ID existence 
clear-content .\UsersForBulk.txt
clear-content .\temp.txt
ii .\UsersForBulk.txt
read-host " Please edit user info in the text and excel file 
and then press enter to continue"
$Users = get-content .\UsersForBulk.txt
$count = [int]$Users.count
for ($i = 1; $i -lt $count; $i++)
{
	$User = $Users[$i].split("`"")[1]
	$Fname = $Users[$i].split("`"")[9]
	$Lname = $Users[$i].split("`"")[7]
	$result =Get-ADuser $User
	if ($result -eq $null) {continue} #<------------Go to next loop if ID doesn't exit
	else #<----------------------------------------Remind user to enter a new ID if ID already exists
	{
	$UserNew = $User
	while(Get-ADuser $UserNew)
		{
		$UserNew= read-host "ID $UserNew already exists, please enter a new UserID for $Fname $Lname"
		}
	$Users[$i] = $Users[$i] -replace $User,$UserNew
	}
}
echo $Users > .\UsersForBulk.txt #<------------------Write new modified IDs 
$Ticket = read-host "Please Enter Ticket Number"
$Notes = $Ticket + " - Account Created - "  + (get-date).ToString('MM/dd/yyyy')
$pwd= read-host "Please enter a new password" -assecurestring
write-host -foregroundcolor yellow "Please only enter 'y' for below option if this is for all users, otherwise you need to manually update the user expiration date after this script has been completed!"
$isExpdateSpecified = read-host "does the user expiration date has been specified:Y/N"
if($isExpdateSpecified  -ieq 'y'){
	[DateTime]$Expdate = read-host "Please Enter user expiration date(MM/dd/yyyy)"
}else{$Expdate = (Get-Date).AddDays(365)}

$erroractionpreference = "Stop" #<---------------------Stop script if error happens
#<---------------------------------------------------------Create User ID
# Import-CSV .\Users.csv | foreach `
get-content  .\UsersForBulk.txt | ConvertFrom-CSV -UseCulture | foreach `
{New-Aduser `
-Server $DC -SamAccountName $_.SamAccountName.trim() -Name $_.Name.trim() `
-Displayname $_.Displayname.trim() -Surname $_.Surname.trim() -GivenName $_.GivenName.trim() `
-UserPrincipalName $_.Upn.trim() -Description $_.Description -Office $_.Office `
-ScriptPath $_.ScriptPath.trim() -HomeDrive $_.HomeDrive.trim() -HomeDirectory $_.HomeDirectory.trim() `
-Title $_.Title -Department $_.Department -Company $_.Company -Manager $_.Manager.trim() `
-OtherAttributes @{'info'=$Notes} -Path "OU=Corporate,OU=Users,OU=EnergyAustralia,OU=Users and Computers,DC=domain,DC=internal" -AccountPassword (ConvertTo-SecureString `
 $pwd -AsPlainText  -Force) -AccountExpirationDate $Expdate `
-ChangePasswordAtLogon $true -Enabled $true
}
for ($i = 1; $i -lt $count; $i++)
{
	$ID = $Users[$i].split("`"")[1]
#<------------------------------------------------------------Add user basic group
	Add-ADGroupMember -Identity "xxxxxx" -Member $ID -Server $DC 
}
#<-------------------------------------------------------------Add additional group
$answer  =read-host "Does the user also need other group: Y/N ?"
if($answer -ieq "Y")
{
clear-content .\othergroup.txt
clear-content .\error.txt
$groups=@()
ii .\othergroup.txt
write-host -foregroundcolor yellow "Please make sure you put the right groups and press enter to continue"
read-host " "
	foreach($othergroup in type .\othergroup.txt)
	{#check if the given group exits
		$result = gag $othergroup
		if($result -eq $null)
		{
		echo $othergroup >>.\error.txt
		}else{
		$result =$null
		$groups+=$othergroup}
	}
	for ($i = 1; $i -lt $count; $i++)
	{
		
		foreach($item in $groups)#add the existed groups to user
		{
		agm -Identity $item -Member $Users[$i].split("`"")[1] -Server $DC 
		}
	}
}
#<-----------------------------------------Update user info based on the user type
$type = rh "Please enter user type: 1 2 3 .."
Switch ($type)
{
#<---------------------------------------------------------------Update   user
1 {
	for ($i = 1; $i -lt $count; $i++)
		{
			$ID= $Users[$i].split("`"")[1]
			Remove-ADGroupMember -Identity "xxxx" -Member $ID -Server $DC -Confirm:$false
		}
}
#<---------------------------------------------------------------Update   user
2 {
	for ($i = 1; $i -lt $count; $i++)
		{
			$ID= $Users[$i].split("`"")[1] 
			Remove-ADGroupMember -Identity "xxx" -Member $ID -Server $DC -Confirm:$false
			Set-Aduser -Identity $ID -Server $DC -Manager $null -ChangePasswordAtLogon $false  -AccountExpirationDate $0
			Get-Aduser $ID -Server $DC| Move-ADObject  -TargetPath 	"xxxxx"
		}
	}
}
$erroractionpreference = "Continue"  #<-----------------------Continue with error info print
#<-------------------------------------------------------Create Mailbox
$answer  =read-host "Does the user also need mailbox created: Y/N ?"
if($answer -ieq "Y")
{
	for ($i = 1; $i -lt $count; $i++)
	{
		$ID= $Users[$i].split("`"")[1] 
		$n1 = Get-Random 1,2,3,4
		$n2 = Get-Random 5,6
		$MDB = "EA-MDB-00" + $n1 #Get-Random DB
		$ARC = "EA-ARC-00" + $n2 #Get-Random ArchiveDB
		Enable-Mailbox -Identity $ID -Alias $ID -Database $MDB  -ActiveSyncMailboxPolicy 'Default'
		Enable-Mailbox -Identity $ID -Archive -ArchiveDatabase $ARC
		Set-CASMailbox -Identity $ID -OWAEnabled $false  >$null
		<#enable lync access
		$mail = ck $ID mail
		$SipAddress = "sip:" + $mail
		Enable-CsUser  -Identity $ID -RegistrarPool lyncpool.truenergy.com.au -SipAddress $SipAddress 
		Set-CsUser -Identity $ID -AudioVideoDisabled $True
		#>
	}
}
(get-date).ToString('hh:mm:ss')
if ((cat .\error.txt) -ne $null)
{
wh -foregroundcolor yellow "There are some given groups that cannot be found in AD
Please double check and then add correct ones to user
Once done, You can send email to user, the script will wait few minis to add user home M: access"
ii .\error.txt
}else{wh -foregroundcolor yellow "You can enable the user lync access(if required) and then send 
notification email, the script will wait few mins to add user home M: access"}
#<-----------------------------------------------Grant  user home folder access
$erroractionpreference = "SilentlyContinue" #Ignore error info
for ($i = 1; $i -lt $count; $i++)
{
	$ID= $Users[$i].split("`"")[1] 
	if ( (Test-Path $homefolder$ID) -eq $false)
		{
			new-item -path  $homefolder -name $ID -itemtype directory
		}
	$restemp = gau $ID
	while ($restemp -eq $null)
	{
	Start-Sleep -s 30
	$restemp = gau $ID
	}
	Add-NTFSAccess -Path $homefolder$ID  -Account EE\$ID -AccessRights Modify
}
if($type -eq "6"){
	for ($i = 1; $i -lt $count; $i++){
		$ID= $Users[$i].split("`"")[1] 
		try{
			Get-Aduser $ID -Server $DC | Move-ADObject -TargetPath `
			"OU=TeleTech,OU=External,OU=Users and Computers,DC=domain,DC=internal"
		}catch{
			echo "$ID has not been moved to TeleTech OU" >> .\temp.txt
		}finally{}
	} 
}
if((cat .\temp.txt) -ne $null){
wh -foregroundcolor yellow "There are some accounts that haven't been moved to the correct OU, please check and move them manually"
ii .\temp.txt
}
# Get-CsUser $Users[-1]|select RegistrarPool,DisplayName
Get-NTFSAccess -Path $homefolder$Users[-1] |?{$_.account -eq "EE\$Users[-1]"}|select-object FullName, Account, AccessRights
write-host -foregroundcolor yellow "The IDs have been created successfully!"